var Page = PageView.extend({
    tplId: "pageTpl",
    hasPostByShake: false,
    initElView: function () {
        var that = this;
        Page.instance = this;
        var url = window.location.href;
        //url = 'https://www.cdmates.com/market/flow/1/afuyfk';
        //这种url我tmd怎么处理
        //var absoluteContextPath ="https://www.cdmates.com";
        var params = (url.split("activity/flow")[1]).split('?')[0].split("/")[1];
        this.activityId = params;
        $.ajax({
            method: "POST",
            url: absoluteContextPath + '/market/flow/' + params,
            //url:'https://www.cdmates.com/market/flow/1/lottery?tel=18359219330',
            beforeSend: function (request) {
                request.setRequestHeader("X-Requested-With", "XMLHttpRequest");
            },
            success: function (res) {
                that.$el.html(template('pageTpl', res.data));
                document.title = res.data.title;
                that.$el.find('.js_rule_container').html(res.data.rule);
                that.bindGetBtn();
                if (res.data.hasJoined) {
                    that.setCountDown(res.data.remainTime);
                }
                that.bindScroll(res.data);
            }
        });
    },

    bindGetBtn: function () {
        var that = this;
        this.$el.find('.js_get_btn').bind('click', function () {
            if (that.checkTel(that.$el.find('#js_tel').val())) {
                that.renderShakePage({tel: that.$el.find('#js_tel').val()});
            }
            else {
                alert('请输入正确的手机号码');
            }
        })
    },

    checkTel: function (tel) {
        var pattern = /^1[34578]\d{9}$/;
        return pattern.test(tel) ? true : false;
    },

    renderShakePage: function (data) {
        window.location.href = absoluteContextPath + '/activity/flow/shake/' + this.activityId + '?tel=' + data.tel + '&uuid=' + this.getParamFromUrl('uuid');
        // this.$el.find('.first-view').hide();
        // this.$el.find('.shake-view').show();
        // this.$el.find('.js_tel_number').html(data.tel);
        // this.bindShake(data.tel);
    },

    bindShake: function (tel) {
        var SHAKE_THRESHOLD = 800;
        var last_update = 0;
        var x = y = z = last_x = last_y = last_z = 0;

        if (window.DeviceMotionEvent) {
            window.addEventListener('devicemotion', deviceMotionHandler, false);
        } else {
            alert('本设备不支持devicemotion事件');
        }

        function deviceMotionHandler(eventData) {
            var acceleration = eventData.accelerationIncludingGravity;
            var curTime = new Date().getTime();

            if ((curTime - last_update) > 100) {
                var diffTime = curTime - last_update;
                last_update = curTime;
                x = acceleration.x;
                y = acceleration.y;
                z = acceleration.z;
                var speed = Math.abs(x + y + z - last_x - last_y - last_z) / diffTime * 10000;
                var status = document.getElementById("status");

                if (speed > SHAKE_THRESHOLD) {
                    Page.instance.shakeEventDidOccur(tel);
                }
                last_x = x;
                last_y = y;
                last_z = z;
            }
        }

        function doResult() {
            document.getElementById("result").className = "result";
            document.getElementById("loading").className = "loading loading-show";
            setTimeout(function () {
                //document.getElementById("hand").className = "hand";
                document.getElementById("result").className = "result result-show";
                document.getElementById("loading").className = "loading";
            }, 1000);
        }
    },

    shakeEventDidOccur: function (tel) {
        var that = this;
        that.$el.find("#js_music_effect")[0].play();
        if (!that.hasPostByShake) {
            that.hasPostByShake = true;
            var url = absoluteContextPaht + "/market/flow/" + that.activityId + "/lottery?tel=" + tel;
            $.ajax({
                method: "POST",
                url: url,
                beforeSend: function (request) {
                    request.setRequestHeader("X-Requested-With", "XMLHttpRequest");
                },
                success: function (res) {
                    if (res.result == 0) {
                        alert('恭喜您中了' + res.data.prize + "流量券");
                        window.location.reload();
                    }
                    else {
                        that.hasPostByShake = false;
                        alert(res.msg);
                    }
                }
            });
        }
    },

    setCountDown: function (time) {
        var that = this;
        var fomatTime;
        setInterval(function () {
            if (time > 0) {
                fomatTime = that.formatTime(time);
                that.$el.find('.js_count_down').html(fomatTime.minute + ":" + fomatTime.second);
                time--;
            }
            else {
                that.$el.find('.js_count_down').html('已过期');
            }
        }, 1000);
    },

    formatTime: function (second) {
        var result = {};
        result.minute = parseInt(second / 60);
        result.second = second % 60;
        if (result.second < 10) {
            result.second = "0" + result.second;
        }
        return result;
    },

    bindScroll: function (data) {
        if (_.size(data.list) > 3) {
            var $all_user_wrap = $(".prize-list-wrap"); // 用户信息父元素
            var speed = 1; // 步长
            var $wrapHeight = $all_user_wrap.height(); // 不带单位 的height
            var $wrapTop = $all_user_wrap.position().top;
            moveUp(); // 开启定时器 （默认）
            function moveUp() {
                timer = setInterval(function () {
                    $wrapTop -= speed;
                    if ($wrapTop <= -$wrapHeight / 2) {
                        $wrapTop = 0;
                    }
                    $all_user_wrap.css('top', $wrapTop + "px"); // 设置父元素的top值
                }, 30);
            }

            // 停止向上轮播
            function stopMoveUp() {
                clearInterval(timer);
            }
        }
    },

    getParamFromUrl: function (key) {
        window.location.href得到URL
        var sHref = window.location.href;
        //取出不带＃的URL
        sHref = sHref.split('#')[0];
        var args = sHref.split("?");
        var retval = "";
        /*参数为空*/
        if (args[0] == sHref) {
            return retval;
            /*无需做任何处理*/
        }
        var str = args[1];
        args = str.split("&");
        for (var i = 0; i < args.length; i++) {
            str = args[i];
            var arg = str.split("=");
            if (arg.length <= 1) continue;
            if (arg[0] == key) retval = arg[1];
        }
        //if(!retval){
        //    //alert('url中的' + key + '参数为空');
        //    console.log('url中的' + key + '参数为空');
        //}
        return retval;

    }
});
Page.instance = null;